package com.zlcx.tz.live.web;

import com.zlcx.tz.live.common.annotation.AutoLog;
import com.zlcx.tz.live.common.annotation.RepeatSubmit;
import com.zlcx.tz.live.exception.BusinessException;
import com.zlcx.tz.live.exception.CheckParamException;
import com.zlcx.tz.live.exception.CheckRunException;
import com.zlcx.tz.live.service.impl.LiveComplaintService;
import com.zlcx.tz.live.service.impl.TencentImageCheckService;
import com.zlcx.tz.live.service.impl.UploadService;
import com.zlcx.tz.live.vo.ComplaintRoomBody;
import com.zlcx.tz.live.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.ArrayList;
import java.util.List;
import static com.zlcx.tz.live.constant.ResultStatus.IMAGE_VIOLATION;

/**
 * <p></p>
 * <PRE>
 * <BR>    修改记录
 * <BR>-----------------------------------------------
 * <BR>    修改日期         修改人          修改内容
 * </PRE>
 *
 * @author zl
 * @version 1.0
 * @date Created in 2019/4/18 15:46
 * @copyright: Copyright (c) founders
 */
@Controller
@Slf4j
@Api(tags = {"举报"}, description = "举报相关接口")
@RequestMapping("complaint")
public class ComplaintController extends BaseController {


    private static final int MAX_UPLOAD_IMAGES = 1;
    @Autowired
    LiveComplaintService complaintService;

    @Autowired
    private UploadService uploadService;

    @Autowired
    private TencentImageCheckService tencentImageCheckService;

    @AutoLog
    @PreAuthorize("isAuthenticated()")
    @RepeatSubmit
    @ApiOperation(value = "举报", notes = "举报")
    @PostMapping(value = "/submit/{roomId}/{userId}")
    public ResponseEntity<ResultVO> complaintRoom(@ApiParam(value = "token", required = true) @RequestHeader String authorization,
                                                  @ApiParam(value = "房间id", required = true) @PathVariable Long roomId,
                                                  @ApiParam(value = "举报人id", required = true) @PathVariable Long userId,
                                                  @ApiParam(value = "举报类型：1-反动言论，2-不雅内容，3-人身攻击，4-广告营销", required = true) @RequestParam Integer complaintType,
                                                  @ApiParam(value = "被举报人id", required = false) @RequestParam(required = false) Long complainedUserId,
                                                  @ApiParam(value = "其他信息") @RequestBody ComplaintRoomBody complaintRoomBody
    ) {

        try {

            complaintService.complaint(roomId, userId, complaintType, complainedUserId, complaintRoomBody);

            return ResponseEntity.ok(successState());

        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("举报失败，roomId={},userId={},complaintType={},complainedUserId={}", roomId, userId, complaintType, complainedUserId, e);
            throw new CheckRunException("举报失败!", e);
        }

    }

    @AutoLog
    @PreAuthorize("isAuthenticated()")
    @RepeatSubmit
    @ApiOperation(value = "举报群组或个人", notes = "举报群组或个人")
    @PostMapping(value = "/common")
    public ResponseEntity<ResultVO> complaintGroupOrUser(@ApiParam(value = "token", required = true) @RequestHeader String authorization,
                                                         @ApiParam(value = "举报人id", required = true) @RequestParam Long userId,
                                                         @ApiParam(value = "举报类型：1-反动言论，2-色情内容，3-人身攻击，4-广告营销", required = true) @RequestParam Integer complaintType,
                                                         @ApiParam(value = "被举报对象类型：1-个人，2-群组", required = true) @RequestParam Integer complainedObjType,
                                                         @ApiParam(value = "被举报人id（举报个人必填）", required = false) @RequestParam(required = false) Long complainedUserId,
                                                         @ApiParam(value = "被举群组id（举报群组必填）", required = false) @RequestParam(required = false) String complainedGroupId,
                                                         @ApiParam(value = "其他信息") @RequestBody ComplaintRoomBody complaintRoomBody
    ) {

        try {

            log.info("[complaintGroupOrUser]举报群组或个人,userId={},complaintType={},complainedObjType={},complainedUserId={},complainedGroupId={} complaintRoomBody = {}", userId, complaintType, complainedObjType, complainedUserId, complainedGroupId, complaintRoomBody);


            return ResponseEntity.ok(successState());

        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("举报群组或个人失败,userId={},complaintType={},complainedObjType={},complainedUserId={},complainedGroupId={}", userId, complaintType, complainedObjType, complainedUserId, complainedGroupId, e);
            throw new CheckRunException("举报群组或个人失败!", e);
        }

    }

    @AutoLog
    @PreAuthorize("isAuthenticated()")
    @RepeatSubmit
    @ApiOperation(value = "举报日志或评论", notes = "举报日志或评论")
    @PostMapping(value = "/diary")
    public ResponseEntity<ResultVO> complaintDiary(@ApiParam(value = "token", required = true) @RequestHeader String authorization,
                                                   @ApiParam(value = "举报人id", required = true) @RequestParam Long userId,
                                                   @ApiParam(value = "举报类型：1-反动言论，2-色情内容，3-人身攻击，4-广告营销", required = true) @RequestParam Integer complaintType,
                                                   @ApiParam(value = "被举报对象类型：1-日志，2-评论", required = true) @RequestParam Integer complainedObjType,
                                                   @ApiParam(value = "日志id", required = false) @RequestParam(required = false) Long diaryId,
                                                   @ApiParam(value = "评论id（举报评论必填）", required = false) @RequestParam(required = false) Long replyId,
                                                   @ApiParam(value = "其他信息") @RequestBody ComplaintRoomBody complaintRoomBody
    ) {

        try {

            log.info("[complaintDiary]举报日志或评论,userId={},complaintType={},complainedObjType={},diaryId={},replyId={} complaintRoomBody = {}", userId, complaintType, complainedObjType, diaryId, replyId, complaintRoomBody);
            return ResponseEntity.ok(successState());

        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("举报日志或评论失败,userId={},complaintType={},complainedObjType={},diaryId={},replyId={}", userId, complaintType, complainedObjType, diaryId, replyId, e);
            throw new CheckRunException("举报日志或评论失败!", e);
        }

    }

    @AutoLog
    @ApiOperation(value = "图片鉴黄", notes = "图片鉴黄")
    @PostMapping(value = "/picCheck/{roomId}/{userId}")
    public ResponseEntity<ResultVO> picCheck(
            @ApiParam(value = "房间id", required = true) @PathVariable Long roomId,
            @ApiParam(value = "用户id", required = true) @PathVariable Long userId,
            @ApiParam(value = "图片", required = true) @RequestBody MultipartFile file) {

        try {

            complaintService.picCheck(roomId, userId, file);
            return ResponseEntity.ok(successState());

        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("图片鉴黄失败，roomId={},userId={}", roomId, userId, e);
            throw new CheckRunException("图片鉴黄失败!", e);
        }

    }


    @AutoLog
    @PreAuthorize("isAuthenticated()")
    @ApiOperation(value = "举报图片上传", notes = "举报图片上传")
    @RequestMapping(value = "/upload/image", method = RequestMethod.POST)
    public ResponseEntity<ResultVO> uploadImg(@ApiParam(value = "图片") @RequestBody MultipartFile[] files) {
        if (files.length > MAX_UPLOAD_IMAGES) {
            throw new CheckParamException("最多上传" + MAX_UPLOAD_IMAGES + "张图片！");
        }
        List<String> imageUrls = new ArrayList<>();

        try {
            for (MultipartFile file : files) {
                String imageUrl = uploadService.uploadComplaintImg(currentUserId(), file);
                imageUrls.add(imageUrl);
            }

            for (String url : imageUrls) {
                Boolean flag = tencentImageCheckService.imageIsNomal(tencentImageCheckService.checkImg(url));
                if (!flag) {
                    uploadService.deleteFile(url);
                    ResultVO resultVO = new ResultVO(IMAGE_VIOLATION.getCode(), IMAGE_VIOLATION.getTips(), null);
                    return ResponseEntity.ok(resultVO);
                }
            }
            return ResponseEntity.ok(successState(imageUrls));

        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("举报图片上传失败,userId={}", currentUserId(), e);
            throw new CheckRunException("举报图片上传失败!", e);
        }
    }


}
